import { Directive } from 'vue'

export const vLongpress: Directive = {
  mounted(el: HTMLElement, binding) {
    let timer: number | null = null
    
    const start = (e: Event) => {
      if (timer === null) {
        timer = setTimeout(() => {
          binding.value(e)
        }, 1000) // 1秒长按
      }
    }
    
    const cancel = () => {
      if (timer !== null) {
        clearTimeout(timer)
        timer = null
      }
    }
    
    el.addEventListener('mousedown', start)
    el.addEventListener('touchstart', start)
    el.addEventListener('mouseup', cancel)
    el.addEventListener('mouseleave', cancel)
    el.addEventListener('touchend', cancel)
  }
}

// 使用方式: <button v-longpress="handleLongPress">长按</button>